<!DOCTYPE html>
<html class="x-admin-sm" style="overflow-y: hidden">
<head>
    <th:block th:insert="head/head :: common_head"></th:block>
    <script type="text/javascript" th:src="@{/jsfiles/xm-select.js?t=20813}" charset="utf-8"></script>
    <!-- 高德地图 API -->
    <script src="https://webapi.amap.com/maps?v=2.0&key=6f2409fb651e7a7831482d0df918e001&plugin=AMap.PolygonEditor"></script>

    <style>
        /* 主题变量定义 浅色*/
        :root {
            --bg-color: #f8f9fa;
            --text-color: #333;
            --panel-bg: #fff;
            --btn-orange: #FF9933;
            --btn-purple: #9966CC;
            --btn-green: #33CC99;
            --btn-danger: #FF3333;
            --highlight-blue: #0066CC; /* 选中操作文字色 */
            --highlight-green: #009966; /* 更新成功文字色 */
            --highlight-red: #FF3333; /* 删除操作文字色 */
            --jianghan-color: #0066CC;
            --jiangan-color: #0099CC;
            /* 文字大小配置 */
            --status-font-size: 14px;
            --instructions-font-size: 14px;
            --coordinate-font-size: 14px;
            --info-font-size: 14px;
            --draw-tip-font-size: 16px; /* 绘制提示文字大小 */
        }

        /* 深色主题变量 */
        .theme-dark {
            --bg-color: #1F2D44;
            --text-color: #fff;
            --panel-bg: #1F2D44;
            --btn-orange: #FF9933;
            --btn-purple: #9966CC;
            --btn-green: #33CC99;
            --btn-danger: #FF3333;
            --highlight-blue: #00CCFF;
            --highlight-green: #33CC99;
            --highlight-red: #FF6666;
            --jianghan-color: #0099FF;
            --jiangan-color: #00CCFF;
        }

        /* 绘制提示高亮样式 */
        .draw-tip {
            font-size: var(--draw-tip-font-size);
            line-height: 1.8;
        }
        .draw-tip-highlight {
            color: var(--btn-danger);
            font-weight: bold;
            font-size: 17px;
        }

        /* 其余样式保持不变 */
        .left-panel {
            background: var(--panel-bg);
            height: calc(100vh - 70px);
            border-radius: 8px;
            padding: 20px;
            color: var(--text-color);
            box-shadow: 0 0 10px rgba(0,0,0,0.1);
            overflow-y: auto;
        }
        .control-panel {
            width: 100%;
            margin: 20px 0;
            padding: 0 15px;
            box-sizing: border-box;
        }
        .panel-title {
            font-size: 16px;
            font-weight: bold;
            color: var(--text-color);
            margin-bottom: 15px;
            padding-bottom: 5px;
            border-bottom: 1px solid #e6e6e6;
        }
        .btn-group {
            display: flex;
            flex-wrap: wrap;
            margin: -5px;
        }
        .btn-group .layui-btn {
            flex: 0 0 calc(25% - 10px);
            max-width: calc(25% - 10px);
            height: 40px;
            line-height: 40px;
            padding: 0;
            margin: 5px;
            box-sizing: border-box;
            border-radius: 6px;
            text-align: center;
        }
        .layui-btn-orange { background: #FF9933; border-color: #FF9933; }
        .layui-btn-purple { background: #9966CC; border-color: #9966CC; }
        .layui-btn-green  { background: #33CC99; border-color: #33CC99; }
        .layui-btn-danger { background: #FF3333; border-color: #FF3333; }
        .layui-btn-theme  { background: #6699FF; border-color: #6699FF; }
        .polygon-selected {
            strokeColor: #FF3333 !important;
            strokeWeight: 4 !important;
            fillColor: #FF333344 !important;
            z-index: 100 !important;
        }
        .edit-info{
            color: var(--text-color);
            font-size: var(--info-font-size);
        }
        .left-status, .left-operation, .left-coordinate {
            line-height: 1.6;
            margin-bottom: 10px;
        }
        .left-status {
            font-size: var(--status-font-size);
        }
        .left-operation {
            font-size: var(--instructions-font-size);
        }
        .left-coordinate {
            font-size: var(--coordinate-font-size);
        }
        .left-status p, .left-coordinate p {
            margin: 5px 0;
        }
        .left-operation h4, .left-coordinate h4 {
            font-size: 16px;
            color: var(--highlight-blue);
            margin: 8px 0 5px;
        }
        .left-operation ol {
            padding-left: 20px;
            margin: 5px 0;
        }
        .left-operation li {
            margin: 3px 0;
        }
        .left-coordinate ul {
            padding-left: 20px;
            margin: 5px 0;
        }
        .left-panel b { color: var(--btn-orange); }
        .map-operation-buttons {
            position: absolute;
            bottom: 30px;
            right: 30px;
            z-index: 90;
            display: flex;
            flex-direction: column;
            gap: 12px;
        }
        .map-btn {
            padding: 12px 16px;
            border: none;
            border-radius: 6px;
            color: white;
            cursor: pointer;
            font-size: 15px;
            font-weight: 500;
            transition: all 0.2s;
            box-shadow: 0 2px 8px rgba(0,0,0,0.2);
        }
        .map-btn.start-edit { background-color: #33CC99; }
        .map-btn.stop-edit { background-color: #FF9933; }
        .map-btn.reset { background-color: #6699FF; }
        .map-btn.save {
            background-color: #0066CC;
            border: 1px solid #0088FF;
        }
        .map-btn.save:disabled {
            background-color: #99BBEE;
            cursor: not-allowed;
            opacity: 0.7;
        }
        .map-btn.layui-btn-danger {
            background-color: var(--btn-danger);
            margin-top: 8px;
        }
        .map-btn.layui-btn-danger:hover {
            background-color: #e60000;
            box-shadow: 0 3px 10px rgba(255,51,51,0.3);
        }
        .map-btn.layui-btn-purple {
            background-color: #9966CC;
            border-color: #9966CC;
        }
        .map-btn.layui-btn-purple:hover {
            background-color: #8855BB;
            box-shadow: 0 3px 10px rgba(153,102,204,0.3);
        }
        .map-panel {
            height: calc(100vh - 80px);
            border-radius: 8px;
            overflow: hidden;
            position: relative;
        }
        #mapContainer { width: 100%; height: 100%; }
        .filter-container {
            position: absolute;
            top: 15px;
            left: 15px;
            z-index: 80;
            background-color: rgba(255, 255, 255, 0.9);
            padding: 10px 15px;
            border-radius: 6px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.15);
        }
        .theme-dark .filter-container {
            background-color: rgba(31, 45, 68, 0.9);
        }
        .theme-dark .layui-form-label { color: #fff; }
        .theme-dark .layui-input,
        .theme-dark .layui-select,
        .theme-dark .layui-textarea {
            background-color: #304156;
            border-color: #4E5D6C;
            color: #fff;
        }
        .filter-container .layui-btn {
            height: 38px;
            line-height: 38px;
            padding: 0 15px;
        }
        .theme-dark .filter-container .layui-btn-primary {
            background-color: #304156;
            border-color: #4E5D6C;
            color: #fff;
        }
        .theme-dark .filter-container .layui-btn-primary:hover {
            background-color: #4E5D6C;
        }
        .map-loading {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            display: flex;
            align-items: center;
            justify-content: center;
            background: rgba(0,0,0,0.5);
            color: white;
            z-index: 100;
            font-size: 18px;
        }
        .map-error {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            display: none;
            align-items: center;
            justify-content: center;
            background: rgba(0,0,0,0.7);
            color: white;
            z-index: 100;
            font-size: 18px;
            flex-direction: column;
        }
        .map-error button {
            margin-top: 15px;
            padding: 8px 20px;
            background: #FF3333;
            border: none;
            color: white;
            border-radius: 4px;
            cursor: pointer;
        }
        .theme-dark .amap-logo,
        .theme-dark .amap-copyright {
            opacity: 0.8 !important;
        }
    </style>
</head>
<body>
<div class="layui-fluid">
    <div class="layui-row layui-col-space15">
        <!-- 左侧面板 -->
        <div class="layui-col-md2">
            <div class="left-panel">
                <div class="control-panel">
                    <div class="panel-title">控制面板</div>
                    <div class="btn-group">
                        <button class="layui-btn layui-btn-orange" id="addFenceBtn">新增围栏</button>
                        <button class="layui-btn layui-btn-theme" id="themeToggle">切换主题</button>
                    </div>
                </div>

                <div class="control-panel">
                    <div class="panel-title">当前围栏状态</div>
                    <div class="left-status">
                        <p>无选中围栏</p>
                    </div>
                </div>

                <div class="control-panel">
                    <div class="panel-title">操作说明</div>
                    <div class="left-operation">
                        <ol>
                            <li>点击<b>修改名称</b>可编辑围栏名称</li>
                            <li>点击<b>开始编辑</b>可调整围栏形状</li>
                            <li>编辑完成后点击<b>结束编辑</b>确认修改</li>
                            <li>需要撤销修改点击<b>还原</b>恢复初始状态</li>
                            <li>确认结束编辑后点击<b>保存编辑</b>保存网格</li>
                            <li>不需要的围栏可点击<b>删除网格</b>移除</li>
                        </ol>
                    </div>
                </div>

                <div class="control-panel">
                    <div class="panel-title">围栏坐标</div>
                    <div class="left-coordinate">
                        <p>请选中一个围栏查看</p>
                    </div>
                </div>

                <div class="control-panel">
                    <div class="panel-title">操作信息</div>
                    <div class="edit-info">
                        这里显示操作信息
                    </div>
                </div>
            </div>
        </div>

        <!-- 中间地图区域 -->
        <div class="layui-col-md10">
            <div class="map-panel">
                <div class="filter-container">
                    <form class="layui-form" lay-filter="filterForm">
                        <div class="layui-form-item">
                            <div class="layui-inline">
                                <label class="layui-form-label">机构筛选</label>
                                <div class="layui-input-inline">
                                    <div id="xzjg" name="xzjg" style="width: 203.8px"></div>
                                </div>
                            </div>
                            <div class="layui-inline">
                                <label class="layui-form-label">分组</label>
                                <div class="layui-input-inline">
                                    <div id="group" name="group" style="width: 203.8px"></div>
                                </div>
                            </div>
                            <div class="layui-inline">
                                <button class="layui-btn layui-btn-theme" type="button" id="searchBtn">搜索</button>
                                <button class="layui-btn layui-btn-primary" type="button" id="resetBtn" style="margin-left: 5px;">重置</button>
                            </div>
                        </div>
                    </form>
                </div>
                <div class="map-loading">
                    <i class="layui-icon layui-icon-loading-1 layui-anim layui-anim-rotate layui-anim-loop"></i>
                    地图加载中...
                </div>
                <div class="map-error">
                    <p>地图加载失败，请检查网络连接或API Key</p>
                    <button onclick="retryLoadMap()">重试加载</button>
                </div>
                <div id="mapContainer"></div>
            </div>
        </div>
    </div>
</div>

<th:block th:insert="head/head :: common_jsfiles"></th:block>
<script>
    // 后端地址
    var url = "[[${serverUrl}]]/";

    // 全局变量
    var map;
    var mapLoaded = false;
    var allPolygons = [];  // 存储所有围栏多边形
    var isEditing = false;
    var currentEditor = null;  // 当前激活的编辑器
    var currentPolygon = null; // 当前正在编辑的多边形
    var operationButtons = null; // 当前显示的按钮
    var selectedPolygon = null; // 当前选中的围栏
    var isModified = false;    // 标记围栏是否被修改
    var isAddingFence = false; // 是否处于新增围栏状态
    var newFenceEditor = null; // 新增围栏编辑器
    var tempFence = null; // 临时围栏对象
    var xzjg = null; // 行政机构
    var wgfz = null; // 网格分组
    var layerindex = null; // 弹出层
    var newFence = null; // 新围栏
    let fenceList = null; // 历史网格
    var editFence = null; // 待修改保存的围栏

    // 计算多边形中心坐标
    function getPolygonCenter(path) {
        if (!path || path.length === 0) return [0, 0];

        let lngSum = 0;
        let latSum = 0;
        const pointCount = path.length;

        path.forEach(point => {
            const lng = Array.isArray(point) ? point[0] : point.lng;
            const lat = Array.isArray(point) ? point[1] : point.lat;
            lngSum += lng;
            latSum += lat;
        });

        return [lngSum / pointCount, latSum / pointCount];
    }

    // 清除地图元素（围栏+标签）
    function clearMapElements() {
        allPolygons.forEach(polygon => {
            const textLabel = polygon.getExtData().textLabel;
            if (textLabel) map.remove(textLabel);
            map.remove(polygon);
        });
        allPolygons = [];
    }

    // 初始化函数
    function init(iniData) {
        console.info("iniData:" + JSON.stringify(iniData));

        // 按官方示例结构（filterable: true，filterDone在顶层）
        xzjg = xmSelect.render({
            el: '#xzjg',
            autoRow: true,
            filterable: true,
            filterDone: function(val, list) {
                const self = this; // 组件实例
                const expandValues = []; // 收集需要展开的节点value

                // 1. 递归收集所有节点的value（包括所有层级）
                function collectExpandKeys(node) {
                    expandValues.push(node.value); // 收集当前节点
                    if (node.children && node.children.length) {
                        node.children.forEach(child => collectExpandKeys(child)); // 递归收集子节点
                    }
                }
                // 遍历筛选后的list，收集所有节点
                list.forEach(node => collectExpandKeys(node));

                xzjg.changeExpandedKeys(expandValues);

                // 3. 打印清理后的筛选结果（避免循环引用报错）
                const cleanList = list.map(node => ({
                    name: node.name,
                    value: node.value,
                    children: node.children ? node.children.map(child => ({
                        name: child.name,
                        value: child.value
                    })) : []
                }));
                console.log('筛选结果：', cleanList);
                console.log('通过expandedKeys展开的节点：', expandValues);
            },
            tree: {
                show: true,
                showFolderIcon: true,
                showLine: true,
                indent: 20,
                strict: false,
                expandedKeys: [-3], // 初始展开节点（符合官方配置）
            },
            toolbar: { show: true, list: ['ALL', 'REVERSE', 'CLEAR'] },
            height: 'auto',
            data: () => iniData.tXzjgTree
        });

        wgfz = xmSelect.render({
            el: '#group',
            autoRow: true,
            filterable: true,
            filterDone: function(val, list) {
                const self = this; // 组件实例
                const expandValues = []; // 收集需要展开的节点value

                // 1. 递归收集所有节点的value（包括所有层级）
                function collectExpandKeys(node) {
                    expandValues.push(node.value); // 收集当前节点
                    if (node.children && node.children.length) {
                        node.children.forEach(child => collectExpandKeys(child)); // 递归收集子节点
                    }
                }
                // 遍历筛选后的list，收集所有节点
                list.forEach(node => collectExpandKeys(node));

                xzjg.changeExpandedKeys(expandValues);

                // 3. 打印清理后的筛选结果（避免循环引用报错）
                const cleanList = list.map(node => ({
                    name: node.name,
                    value: node.value,
                    children: node.children ? node.children.map(child => ({
                        name: child.name,
                        value: child.value
                    })) : []
                }));
                console.log('筛选结果：', cleanList);
                console.log('通过expandedKeys展开的节点：', expandValues);
            },
            tree: {
                show: true,
                showFolderIcon: true,
                showLine: true,
                indent: 20,
                strict: false,
                expandedKeys: [-3], // 初始展开节点（符合官方配置）
            },
            toolbar: { show: true, list: ['ALL', 'REVERSE', 'CLEAR'] },
            height: 'auto',
            data: () => iniData.zhdtWgfzTree
        });

        // 历史网格
        fenceList = iniData.zhdtWgxxList;

        // 加载用户主题偏好
        const savedTheme = localStorage.getItem('mapTheme');
        if (savedTheme === 'dark') {
            document.body.classList.add('theme-dark');
        }

        // 绑定主题切换按钮
        document.getElementById('themeToggle').addEventListener('click', toggleTheme);

        // 绑定新增围栏按钮事件
        document.getElementById('addFenceBtn').addEventListener('click', startAddFence);

        // 初始化地图
        initMap();

        // 初始化Layui表单和按钮事件
        layui.use('form', function () {
            var form = layui.form;

            // 绑定搜索按钮点击事件
            document.getElementById('searchBtn').addEventListener('click', () => filterFences());

            // 绑定重置按钮点击事件
            document.getElementById('resetBtn').addEventListener('click', function () {
                form.val('filterForm', { 'area': '', 'group': '' });
                filterFences();
                document.querySelector('.edit-info').textContent = '筛选已重置，显示所有围栏';
            });
        });
    }

    // 初始化界面数据
    function initMain() {
        let jsonData = { timestamp: new Date().getTime() };
        let sendStr = {
            data: encrypt_str(JSON.stringify(jsonData), localStorage.getItem("a"), localStorage.getItem("b"))
        };
        post_json_table(url + "zhdt/main/init", JSON.stringify(sendStr), "信息加载中...", init);
    }

    // 显示筛选结果信息
    function showFilterInfo(data) {
        layui.use('form', function () {
            const xzjgValue = xzjg.getValue('name') || '全部机构';
            const groupValue = wgfz.getValue('name') || '全部分组';
            const fenceList = data.cxjg.listInfo || [];
            const total = data.cxjg.pageInfo.total || 0;

            document.querySelector('.edit-info').textContent =
                `已筛选：${xzjgValue} · ${groupValue}，共${total}个围栏`;

            clearMapElements();

            fenceList.forEach(fence => {
                try {
                    const path = JSON.parse(fence.wglj);
                    const polygon = drawFence(
                        fence.wgmc,
                        path,
                        fence.bkYsdm,
                        fence.zWgfz?.name || '未分组',
                        fence.id || ''
                    );
                    if (polygon) {
                        polygon.setExtData({
                            ...polygon.getExtData(),
                            xzjg: fence.tXzjg?.name,
                            state: fence.state
                        });
                        allPolygons.push(polygon);
                    }
                } catch (e) {
                    console.error(`绘制围栏${fence.wgmc}失败:`, e);
                }
            });
        });
    }

    // 更新左侧面板的围栏状态和坐标
    function updateLeftPanel(fenceName, path) {
        const statusContainer = document.querySelector('.left-status');
        const uniquePoints = [...new Set(path.map(p => `${p.lng},${p.lat}`))];
        const vertexCount = uniquePoints.length;
        statusContainer.innerHTML = `<p>${fenceName}: 已选中 (${vertexCount}个顶点)</p>`;

        const coordinateContainer = document.querySelector('.left-coordinate');
        const coordinateList = path.map((point, index) => {
            const lng = point.lng.toFixed(4);
            const lat = point.lat.toFixed(4);
            return `<li>${lat}, ${lng}</li>`;
        }).join('');

        coordinateContainer.innerHTML = `
            <h4>${fenceName} 围栏坐标</h4>
            <ul>${coordinateList}</ul>
        `;
    }

    // 筛选函数
    function filterFences() {
        layui.use('form', function () {
            const xzjgValue = xzjg.getValue('value') || [];
            const groupValue = wgfz.getValue('value') || [];

            const jsonData = {
                xzjgIds: xzjgValue.length ? xzjgValue : null,
                wgfzIds: groupValue.length ? groupValue : null,
                timestamp: new Date().getTime()
            };

            const sendStr = {
                data: encrypt_str(JSON.stringify(jsonData), localStorage.getItem("a"), localStorage.getItem("b"))
            };
            post_json_table(url + "zhdt/wgxx/query", JSON.stringify(sendStr), "筛选中...", showFilterInfo);
        });
    }

    // 初始化高德地图
    function initMap() {
        document.querySelector('.map-loading').style.display = 'flex';
        document.querySelector('.map-error').style.display = 'none';

        if (typeof AMap === 'undefined') {
            console.error('高德地图API加载失败');
            showMapError();
            return;
        }

        try {
            map = new AMap.Map('mapContainer', {
                center: [114.30, 30.60],
                zoom: 14,
                viewMode: '3D',
                mapStyle: document.body.classList.contains('theme-dark')
                    ? 'amap://styles/darkblue'
                    : 'amap://styles/normal'
            });

            map.on('complete', function () {
                console.log('地图加载完成');
                mapLoaded = true;
                document.querySelector('.map-loading').style.display = 'none';
                drawFences();
                document.querySelector('.edit-info').textContent = '地图加载完成，可开始操作';
            });

            map.on('error', function (e) {
                console.error('地图加载错误:', e);
                showMapError();
            });

            setTimeout(() => {
                if (!mapLoaded) showMapError();
            }, 10000);

        } catch (error) {
            console.error('初始化地图时出错:', error);
            showMapError();
        }
    }

    // 重试加载地图
    function retryLoadMap() {
        initMap();
    }

    // 显示地图加载错误
    function showMapError() {
        document.querySelector('.map-loading').style.display = 'none';
        document.querySelector('.map-error').style.display = 'flex';
        document.querySelector('.edit-info').innerHTML = `<span style="color: var(--highlight-red);">地图加载失败，请检查网络或API Key</span>`;
    }

    // 绘制所有围栏
    function drawFences() {
        clearMapElements();
        fenceList.forEach(fence => {
            const polygon = drawFence(fence.wgmc, JSON.parse(fence.wglj), fence.bkYsdm, fence.wgmc,fence.id);
            if (polygon) allPolygons.push(polygon);
        });
    }

    // 绘制单个围栏（带名称标签）
    function drawFence(name, path, color, group, id) {
        if (!map) return null;

        const polygon = new AMap.Polygon({
            path: path,
            fillColor: color + '33',
            strokeColor: color,
            strokeWeight: 2,
            extData: {
                id: id || '',
                name: name,
                color: color,
                group: group,
                originalPath: [...path],
                currentPath: [...path]
            }
        });

        const center = getPolygonCenter(path);
        const isDarkTheme = document.body.classList.contains('theme-dark');
        const textColor = isDarkTheme ? '#FF3333' : '#333333';

        const textLabel = new AMap.Text({
            position: center,
            text: `<div style="font-size: 12px; font-weight: bold; color: ${textColor}; padding: 2px 5px; background: rgba(255,255,255,0.7); border-radius: 3px;">${name}</div>`,
            anchor: 'center',
            zIndex: 10
        });

        textLabel.setMap(map);
        polygon.setExtData({ ...polygon.getExtData(), textLabel: textLabel });

        // 点击围栏事件 - 新增逻辑控制：新增状态下禁止选中其他围栏
        polygon.on('click', function () {
            if (isAddingFence) {
                // 新增未完成时点击其他围栏：提示并阻止操作
                document.querySelector('.edit-info').innerHTML =
                    `<span style="color: var(--highlight-red); font-weight: bold;">请先保存或取消当前绘制的围栏！</span>`;
                return;
            }

            // 正常选中逻辑
            if (selectedPolygon && selectedPolygon !== this) {
                selectedPolygon.setOptions({
                    strokeColor: selectedPolygon.getExtData().color,
                    strokeWeight: 2,
                    fillColor: selectedPolygon.getExtData().color + '33'
                });
            }

            selectedPolygon = this;
            this.setOptions({
                strokeColor: '#FF3333',
                strokeWeight: 4,
                fillColor: '#FF333344'
            });

            const path = this.getPath();
            const fenceName = this.getExtData().name;
            updateLeftPanel(fenceName, path);
            document.querySelector('.edit-info').innerHTML = `<span style="color: var(--highlight-blue);">已选中围栏：${fenceName}</span>`;

            removeEditButtons();
            createEditButtons(this);
        });

        polygon.setMap(map);
        return polygon;
    }

    // 开始编辑围栏
    function startEditing(currentPolygon) {
        isEditing = true;
        if (currentEditor) currentEditor.close();

        const currentGroup = currentPolygon.getExtData().group;
        const currentName = currentPolygon.getExtData().name;
        const currentColor = currentPolygon.getExtData().color;

        $('.edit-info').html(`当前编辑围栏<span style=\"color:${currentColor}\">【${currentName}】</span>属于【${currentGroup}】，只有同样在【${currentGroup}】里的其他围栏，才会和它产生‘吸附’效果`);

        const relatedPolygons = allPolygons.filter(polygon =>
            polygon.getExtData().group === currentGroup && polygon !== currentPolygon
        );

        currentEditor = new AMap.PolygonEditor(map, currentPolygon);
        currentEditor.addAdsorbPolygons(relatedPolygons);
        currentEditor.open();

        currentEditor.on('end', function () {
            updateFenceInfo(currentPolygon);
            const textLabel = currentPolygon.getExtData().textLabel;
            if (textLabel) {
                const newCenter = getPolygonCenter(currentPolygon.getPath());
                textLabel.setPosition(newCenter);
            }
            updateLeftPanel(currentPolygon.getExtData().name, currentPolygon.getPath());
        });
    }

    // 创建编辑按钮（修改名称按钮放首位并使用紫色）
    function createEditButtons(polygon) {
        // 新增状态下不创建编辑按钮
        if (isAddingFence) return;

        const btnContainer = document.createElement('div');
        btnContainer.className = 'map-operation-buttons';
        btnContainer.id = 'edit-fence-buttons';

        // 1. 修改名称按钮（首位，紫色）
        const renameBtn = document.createElement('button');
        renameBtn.className = 'map-btn layui-btn-purple'; // 使用紫色作为区别色
        renameBtn.textContent = '修改名称';
        renameBtn.onclick = (e) => {
            e.stopPropagation();
            saveFence(polygon); // 复用保存编辑的逻辑
        };

        // 2. 开始编辑按钮
        const startBtn = document.createElement('button');
        startBtn.className = 'map-btn start-edit';
        startBtn.textContent = '开始编辑';
        startBtn.onclick = (e) => {
            e.stopPropagation();
            startEditing(polygon);
            saveBtn.disabled = true;
        };

        // 3. 结束编辑按钮
        const stopBtn = document.createElement('button');
        stopBtn.className = 'map-btn stop-edit';
        stopBtn.textContent = '结束编辑';
        stopBtn.onclick = (e) => {
            e.stopPropagation();
            stopEditing();
            const hasChanged = isPathModified(polygon);
            saveBtn.disabled = !hasChanged;
            isModified = hasChanged;
            document.querySelector('.edit-info').textContent = hasChanged ? '围栏已修改，可点击保存' : '未检测到围栏修改';
        };

        // 4. 还原按钮
        const resetBtn = document.createElement('button');
        resetBtn.className = 'map-btn reset';
        resetBtn.textContent = '还原';
        resetBtn.onclick = (e) => {
            e.stopPropagation();
            resetFence(polygon);
            saveBtn.disabled = false;
            isModified = true;
            document.querySelector('.edit-info').textContent = `已还原【${polygon.getExtData().name}】的初始形状`;
        };

        // 5. 保存编辑按钮
        const saveBtn = document.createElement('button');
        saveBtn.className = 'map-btn save';
        saveBtn.textContent = '保存编辑';
        saveBtn.disabled = true;
        saveBtn.onclick = (e) => {
            e.stopPropagation();
            saveFence(polygon);
            saveBtn.disabled = true;
            isModified = false;
        };

        // 6. 删除网格按钮
        const deleteBtn = document.createElement('button');
        deleteBtn.className = 'map-btn layui-btn-danger';
        deleteBtn.textContent = '删除网格';
        deleteBtn.onclick = (e) => {
            e.stopPropagation();
            deleteFence(polygon);
        };

        // 按顺序添加按钮（修改名称放首位）
        btnContainer.appendChild(renameBtn); // 首位：修改名称
        btnContainer.appendChild(startBtn);
        btnContainer.appendChild(stopBtn);
        btnContainer.appendChild(resetBtn);
        btnContainer.appendChild(saveBtn);
        btnContainer.appendChild(deleteBtn);

        document.querySelector('.map-panel').appendChild(btnContainer);
        operationButtons = btnContainer;
    }

    // 移除编辑按钮
    function removeEditButtons() {
        const oldBtn = document.getElementById('edit-fence-buttons');
        if (oldBtn) {
            oldBtn.remove();
            operationButtons = null;
        }
    }

    // 判断路径是否被修改
    function isPathModified(polygon) {
        const original = polygon.getExtData().originalPath;
        const current = polygon.getPath();

        if (original.length !== current.length) return true;

        for (let i = 0; i < original.length; i++) {
            const o = original[i];
            const c = current[i];
            if (Math.abs(o[0] - c.lng) > 0.0001 || Math.abs(o[1] - c.lat) > 0.0001) {
                return true;
            }
        }
        return false;
    }

    // 删除网格
    let delPolygon;
    function deleteFence(polygon) {
        if (!confirm(`确定要删除网格【${polygon.getExtData().name}】吗？`)) return;

        const fenceId = polygon.getExtData().id;
        var jsonData = { id: fenceId, timestamp: new Date().getTime() };
        var sendStr = {
            data: encrypt_str(JSON.stringify(jsonData), localStorage.getItem("a"), localStorage.getItem("b"))
        };
        post_json_token_back(url + "zhdt/wgxx/del", JSON.stringify(sendStr), "网格删除中...", delFenceBack);
        delPolygon = polygon;
    }

    function delFenceBack(result){
        if (result.code === 3){
            const fenceId = delPolygon.getExtData().id;
            const fenceName = delPolygon.getExtData().name;
            const textLabel = delPolygon.getExtData().textLabel;

            if (textLabel) map.remove(textLabel);
            map.remove(delPolygon);
            allPolygons = allPolygons.filter(item => item.getExtData().id !== fenceId);

            selectedPolygon = null;
            removeEditButtons();

            document.querySelector('.left-status').innerHTML = '<p>无选中围栏</p>';
            document.querySelector('.left-coordinate').innerHTML = '<p>请选中一个围栏查看</p>';
            document.querySelector('.edit-info').innerHTML = `<span style="color: var(--highlight-red);">已删除围栏：${fenceName}</span>`;
        }else{
            document.querySelector('.edit-info').innerHTML = `<span style="color: var(--highlight-red);">删除失败：${result.msg}</span>`;
        }
    }

    // 保存围栏修改
    let edidPolygon;
    function saveFence(polygon) {
        if (!polygon) return;
        edidPolygon = polygon;

        const extData = polygon.getExtData();
        const fenceId = extData.id;
        if (!fenceId) {
            alert("围栏ID不存在，无法保存围栏信息！");
            return;
        }

        const newPath = polygon.getPath().map(p => [p.lng, p.lat]);
        const fenceData = {
            id: fenceId,
            color: extData.color,
            group: extData.group,
            originalPath: newPath,
            currentPath: newPath,
            vertexCount: newPath.length,
            createTime: extData.createTime || new Date().toISOString()
        };

        layerindex = layer.open({
            type: 2,
            title: "围栏信息",
            area: ["680px", "580px"],
            content: "/zhdt/zhdt/wgxx/info?lx=1&id="+fenceId,
            fixed: true,
            maxmin: true,
            shadeClose: false
        });

        editFence = fenceData;
    }

    function doSaveEditFence(jsonData){
        layer.close(layerindex);
        jsonData["fenceData"] = editFence;
        var sendStr = {
            data: encrypt_str(JSON.stringify(jsonData), localStorage.getItem("a"), localStorage.getItem("b"))
        };
        post_json_token_back(url + "zhdt/wgxx/save", JSON.stringify(sendStr), "数据提交中...", saveUpdateFenceBack);
    }

    function saveUpdateFenceBack(result){
        if (result.code === 1) {
            let rtn = decrypt_str(result.data, localStorage.getItem("a"), localStorage.getItem("b"));
            let fenceName = JSON.parse(rtn).wgmc;

            const textLabel = edidPolygon.getExtData().textLabel;
            if (textLabel) {
                const isDarkTheme = document.body.classList.contains('theme-dark');
                const textColor = isDarkTheme ? '#FF3333' : '#333333';
                textLabel.setText(`<div style="font-size: 12px; font-weight: bold; color: ${textColor}; padding: 2px 5px; background: rgba(255,255,255,0.7); border-radius: 3px;">${fenceName}</div>`);
            }

            edidPolygon.setExtData({ ...edidPolygon.getExtData(), name: fenceName });
            document.querySelector('.edit-info').innerHTML = `<span style="color: var(--highlight-green);">【${fenceName}】坐标已同步到数据库</span>`;
        } else {
            document.querySelector('.edit-info').innerHTML = `<span style="color: var(--highlight-red);">【${edidPolygon.getExtData().name}】保存失败：${result.msg || '未知错误'}</span>`;
        }
    }

    // 还原围栏
    function resetFence(polygon) {
        const originalPath = polygon.getExtData().originalPath;
        polygon.setPath(originalPath);
        const textLabel = polygon.getExtData().textLabel;
        if (textLabel) {
            const originalCenter = getPolygonCenter(originalPath);
            textLabel.setPosition(originalCenter);
        }
        updateFenceInfo(polygon);
        updateLeftPanel(polygon.getExtData().name, originalPath);
        alert(`已还原【${polygon.getExtData().name}】的初始形状`);
        isModified = true;
    }

    // 更新围栏信息
    function updateFenceInfo(polygon) {
        const name = polygon.getExtData().name;
        const path = polygon.getPath();
        const coordinateText = path.map(point => `${point.lat.toFixed(4)}, ${point.lng.toFixed(4)}`).join('\n');
        console.log(`${name} 围栏坐标已更新:\n${coordinateText}`);
    }

    // 结束编辑
    function stopEditing() {
        if (currentEditor) {
            currentEditor.close();
            currentEditor = null;
            currentPolygon = null;
            isEditing = false;

            if (selectedPolygon) {
                selectedPolygon.setOptions({
                    strokeColor: '#FF3333',
                    strokeWeight: 4,
                    fillColor: '#FF333344'
                });
            }
        }
    }

    // 开始新增围栏
    function startAddFence() {
        // 如果正在新增，先取消
        if (isAddingFence) {
            cancelAddFence();
            return;
        }

        // 重置状态
        isAddingFence = true;
        if (selectedPolygon) {
            selectedPolygon.setOptions({
                strokeColor: selectedPolygon.getExtData().color,
                strokeWeight: 2,
                fillColor: selectedPolygon.getExtData().color + '33'
            });
            selectedPolygon = null;
        }
        removeEditButtons();

        // 清空左侧面板
        document.querySelector('.left-status').innerHTML = '<p>无选中围栏</p>';
        document.querySelector('.left-coordinate').innerHTML = '<p>请选中一个围栏查看</p>';

        // 优化提示文字：增大字体+高亮双击提示
        document.querySelector('.edit-info').innerHTML = `
            <span class="draw-tip">请在地图上点击开始绘制多边形顶点，
            <span class="draw-tip-highlight">双击结束绘制</span>
            </span>
        `;

        newFenceEditor = new AMap.PolygonEditor(map);
        tempFence = null;
        let tempTextLabel = null;

        newFenceEditor.on('addnode', function (event) {
            setTimeout(() => {
                if (!tempFence) {
                    tempFence = event.target;
                    tempFence.setOptions({
                        strokeColor: '#FF3333',
                        strokeWeight: 4,
                        fillColor: '#FF333344'
                    });
                    createAddButtons();
                }
                if (tempFence && !tempTextLabel) {
                    const center = getPolygonCenter(tempFence.getPath());
                    const isDarkTheme = document.body.classList.contains('theme-dark');
                    const textColor = isDarkTheme ? '#FF3333' : '#333333';
                    tempTextLabel = new AMap.Text({
                        position: center,
                        text: `<div style="font-size: 12px; font-weight: bold; color: ${textColor}; padding: 2px 5px; background: rgba(255,255,255,0.7); border-radius: 3px;">新围栏</div>`,
                        anchor: 'center',
                        zIndex: 10
                    });
                    tempTextLabel.setMap(map);
                    tempFence.setExtData({ textLabel: tempTextLabel });
                } else if (tempTextLabel) {
                    const newCenter = getPolygonCenter(tempFence.getPath());
                    tempTextLabel.setPosition(newCenter);
                }
            }, 300);
        });

        newFenceEditor.on('end', function (event) {
            setTimeout(() => {
                tempFence = event.target;
                const finalPath = tempFence.getPath();

                if (finalPath.length < 3) {
                    alert("围栏顶点不足3个，请重新绘制！");
                    cancelAddFence();
                    return;
                }

                const firstPoint = finalPath[0];
                const lastPoint = finalPath[finalPath.length - 1];
                const isClosed = Math.abs(firstPoint.lng - lastPoint.lng) < 0.00001 &&
                    Math.abs(firstPoint.lat - lastPoint.lat) < 0.00001;
                if (!isClosed) {
                    finalPath.push(firstPoint);
                    tempFence.setPath(finalPath);
                    document.querySelector('.edit-info').textContent = '已自动闭合多边形，可点击保存围栏';
                }

                selectedPolygon = tempFence;
                updateLeftPanel("新围栏", finalPath);
            }, 300);
        });

        newFenceEditor.open();
    }

    // 创建新增围栏按钮
    function createAddButtons() {
        // 移除可能存在的编辑按钮
        removeEditButtons();

        const btnContainer = document.createElement('div');
        btnContainer.className = 'map-operation-buttons';
        btnContainer.id = 'add-fence-buttons';

        const saveBtn = document.createElement('button');
        saveBtn.className = 'map-btn save';
        saveBtn.textContent = '保存围栏';
        saveBtn.onclick = (e) => {
            e.stopPropagation();
            saveNewFence();
        };

        const cancelBtn = document.createElement('button');
        cancelBtn.className = 'map-btn reset';
        cancelBtn.textContent = '取消';
        cancelBtn.onclick = (e) => {
            e.stopPropagation();
            cancelAddFence();
        };

        btnContainer.appendChild(saveBtn);
        btnContainer.appendChild(cancelBtn);
        document.querySelector('.map-panel').appendChild(btnContainer);
        operationButtons = btnContainer;
    }

    // 移除新增围栏按钮
    function removeAddButtons() {
        const oldBtn = document.getElementById('add-fence-buttons');
        if (oldBtn) {
            oldBtn.remove();
            operationButtons = null;
        }
    }

    // 保存新绘制的围栏
    function saveNewFence() {
        if (!tempFence || !newFenceEditor) return;

        newFenceEditor.close();
        const path = tempFence.getPath();
        const tempTextLabel = tempFence.getExtData().textLabel;

        if (path.length < 3) {
            alert("围栏顶点不足3个，无法保存！");
            cancelAddFence();
            return;
        }

        const firstPoint = path[0];
        const lastPoint = path[path.length - 1];
        const isClosed = Math.abs(firstPoint.lng - lastPoint.lng) < 0.00001 &&
            Math.abs(firstPoint.lat - lastPoint.lat) < 0.00001;

        if (!isClosed) path.push(firstPoint);

        const fenceData = {
            color: '#FF3333',
            group: '默认组',
            originalPath: path.map(p => [p.lng, p.lat]),
            currentPath: path.map(p => [p.lng, p.lat]),
            vertexCount: path.length,
            createTime: new Date().toISOString()
        };

        layerindex = layer.open({
            type: 2,
            title: "围栏信息",
            area: ["680px", "580px"],
            content: "/zhdt/zhdt/wgxx/info?lx=0",
            fixed: true,
            maxmin: true,
            shadeClose: false
        });

        newFence = fenceData;
    }

    function doSaveNewFence(jsonData) {
        layer.close(layerindex);
        jsonData["fenceData"] = newFence;
        var sendStr = {
            data: encrypt_str(JSON.stringify(jsonData), localStorage.getItem("a"), localStorage.getItem("b"))
        };
        post_json_token_back(url + "zhdt/wgxx/save", JSON.stringify(sendStr), "数据提交中...", saveNewFenceBack);
    }

    function saveNewFenceBack(result) {
        if (result.code == 1) {
            let rtn = decrypt_str(result.data, localStorage.getItem("a"), localStorage.getItem("b"));
            let fenceName = JSON.parse(rtn).wgmc;

            const textLabel = tempFence.getExtData().textLabel;
            if (textLabel) {
                const isDarkTheme = document.body.classList.contains('theme-dark');
                const textColor = isDarkTheme ? '#FF3333' : '#333333';
                textLabel.setText(`<div style="font-size: 12px; font-weight: bold; color: ${textColor}; padding: 2px 5px; background: rgba(255,255,255,0.7); border-radius: 3px;">${fenceName}</div>`);
            }

            tempFence.setExtData({
                ...tempFence.getExtData(),
                name: fenceName,
                originalPath: tempFence.getPath().map(p => [p.lng, p.lat]),
                currentPath: tempFence.getPath().map(p => [p.lng, p.lat])
            });

            allPolygons.push(tempFence);

            tempFence.on('click', function () {
                if (isAddingFence) {
                    document.querySelector('.edit-info').innerHTML =
                        `<span style="color: var(--highlight-red); font-weight: bold;">请先保存或取消当前绘制的围栏！</span>`;
                    return;
                }

                if (selectedPolygon && selectedPolygon !== this) {
                    selectedPolygon.setOptions({
                        strokeColor: selectedPolygon.getExtData().color,
                        strokeWeight: 2,
                        fillColor: selectedPolygon.getExtData().color + '33'
                    });
                }
                selectedPolygon = this;
                this.setOptions({
                    strokeColor: '#FF3333',
                    strokeWeight: 4,
                    fillColor: '#FF333344'
                });
                const fenceName = this.getExtData().name;
                updateLeftPanel(fenceName, this.getPath());
                document.querySelector('.edit-info').innerHTML = `<span style="color: var(--highlight-blue);">已选中围栏：${fenceName}</span>`;
                removeEditButtons();
                createEditButtons(this);
            });

            document.querySelector('.edit-info').innerHTML = `<span style="color: var(--highlight-green);">已成功创建新围栏【${fenceName}】</span>`;
            cleanupAddFenceState();
        } else {
            document.querySelector('.edit-info').innerHTML = `<span style="color: var(--highlight-red);">新增围栏失败：${result.msg}</span>`;
        }
    }

    // 取消新增围栏
    function cancelAddFence() {
        if (tempFence) {
            const tempTextLabel = tempFence.getExtData().textLabel;
            if (tempTextLabel) map.remove(tempTextLabel);
            map.remove(tempFence);
            tempFence = null;
        }
        if (newFenceEditor) {
            newFenceEditor.off('addnode');
            newFenceEditor.off('end');
            newFenceEditor.close();
            newFenceEditor = null;
        }
        cleanupAddFenceState();
        document.querySelector('.edit-info').textContent = '操作已取消';
    }

    // 清理新增围栏状态
    function cleanupAddFenceState() {
        isAddingFence = false;
        newFenceEditor = null;
        tempFence = null;
        removeAddButtons();
    }

    // 切换主题
    function toggleTheme() {
        const body = document.body;
        const isDark = !body.classList.contains('theme-dark');

        if (isDark) {
            body.classList.add('theme-dark');
            localStorage.setItem('mapTheme', 'dark');
            if (map) map.setMapStyle('amap://styles/darkblue');
        } else {
            body.classList.remove('theme-dark');
            localStorage.setItem('mapTheme', 'light');
            if (map) map.setMapStyle('amap://styles/normal');
        }

        allPolygons.forEach(polygon => {
            const textLabel = polygon.getExtData().textLabel;
            if (textLabel) {
                const textColor = isDark ? '#FF3333' : '#333333';
                textLabel.setText(`<div style="font-size: 12px; font-weight: bold; color: ${textColor}; padding: 2px 5px; background: rgba(255,255,255,0.7); border-radius: 3px;">${polygon.getExtData().name}</div>`);
            }
        });

        if (mapLoaded) {
            clearMapElements();
            drawFences();
        }

        if (tempFence) {
            tempFence.setOptions({
                strokeColor: '#FF3333',
                fillColor: '#FF333344'
            });
        }

        document.querySelector('.edit-info').textContent = `已切换至${isDark ? '深色' : '浅色'}主题`;
    }

    // 页面加载完成后初始化
    window.addEventListener('load', initMain);
</script>
</body>
</html>